package com.jwgf.shell;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created by Jacky on 2016/8/16.
 */
public class SocketClient {

    private static final String DEFAULT_HOST = "127.0.0.1";
    private static final int DEFAULT_PORT = 29599;

    //default socket connection timeout
    public static final int SOCKET_TIMEOUT = 1000;

    private String mHost = DEFAULT_HOST;
    private int mPort = DEFAULT_PORT;

    private BufferedReader mServerReader = null;
    private PrintStream mServerWriter = null;
    private Socket socket = null;

    public void connect() {
        socket = new Socket();
        InetSocketAddress address = new InetSocketAddress(DEFAULT_HOST, DEFAULT_PORT);
        try {
            socket.connect(address, SOCKET_TIMEOUT);
            socket.setSoTimeout(60 * SOCKET_TIMEOUT);
            mServerReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            mServerWriter = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            socket = null;
            mServerReader = null;
            mServerWriter = null;
        }
    }

    public String getServerMessage() {
        try {
            return mServerReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void sendMessageToServer(String message) {
        mServerWriter.println(message);
    }


}
